package com.bargate.domain.spring.expression.util;

import com.google.common.collect.Lists;
import org.springframework.util.NumberUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: EAD-MASTER
 * Date: 02/10/2010
 * Time: 11:26:17
 * To change this template use File | Settings | File Templates.
 */
public class DateParser {

    private static Date getDate(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    public static Date parse(String dateToParse) {
        String[] firstDelimiter = dateToParse.split("/");
        List<Integer> dateSet = Lists.newArrayList();
        if (firstDelimiter.length > 0 && isAValidDate(firstDelimiter)) {
            for (String part : firstDelimiter) {
                dateSet.add(NumberUtils.parseNumber(part, Integer.class));
            }
            return getDate(Integer.parseInt(dateSet.toArray()[0].toString()), Integer.parseInt(dateSet.toArray()[1].toString()), Integer.parseInt(dateSet.toArray()[2].toString()));
        }
        return null;
    }

    private static boolean isAValidDate(String[] firstDelimiter) {
        for (String part : firstDelimiter) {
            if (NumberUtils.parseNumber(part, Integer.class) <= 0) {
                return false;
            }
        }
        return true;
    }
}
